package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.services.impl.UserServiceImpl;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.UUIDUtil;
import com.example.forum.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //  1. 参数校验
        //  1.1 使用注解来判空
        //  1.2 判断两个密码是否相等
        if(!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //  2. 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtil.uuid_32();//  生成盐值
        String encryptPassword = MD5Util.md5Salt(password,salt);//  生成密文
        user.setSalt(salt);
        user.setPassword(encryptPassword);

        //  3. 执行service
        userService.createNormalUser(user);
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        //  1. 调用service
        User user = userService.login(username,password);
        if(user == null) {
            log.error(ResultCode.FAILED_LOGIN.getMessage());
            throw new ApplicationException(ResultCode.FAILED_LOGIN.getMessage());
        }
        //  2. 存储 Session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);

        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult info(HttpServletRequest request,
                          @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id) {
        User user = null;
        //  id==null 返回当前用户信息
        if(id == null) {
            HttpSession session = request.getSession(false);
            if(session == null || session.getAttribute(AppConfig.USER_SESSION_KEY) == null) {
                throw new ApplicationException(ResultCode.FAILED_FORBIDDEN.getMessage());
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
            userService.selectById(user.getId());
        }
        //  id!=null 返回指定用户信息
        else {
            user = userService.selectById(id);
        }
        return AppResult.success(user);
    }

    @ApiOperation("注销")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyinfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickName,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("简介") @RequestParam(value = "remark",required = false) String remark) {
        //  1. 获取用户id
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);

        //  2. 组装更改对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setNickname(nickName);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        //  3. 调用 service
        userService.modifyInfo(updateUser);

        //  4. 获取最新用户信息
        user = userService.selectById(user.getId());

        //  5. 将新用户信息存储到 Session
        HttpSession session = request.getSession();
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);

        return AppResult.success(user);
    }

    @ApiOperation("更改用户密码")
    @PostMapping("/modifypwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("老密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //  1. 检验两次密码是否一致
        if(!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //  2. 获取用户信息
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);

        //  3. 调用service
        userService.modifyPassword(user.getId(),oldPassword,newPassword);

        //  4. 销毁Session
        HttpSession session = request.getSession(false);
        if(session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }

    @PostMapping("/modifyavatar")
    public AppResult modifyAvatar(HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws IOException {
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        userService.modifyAvatarUrl(user.getId(),file);

        //  把新用户信息存储到Session
        user = userService.selectById(user.getId());
        HttpSession session = request.getSession(false);
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);

        response.sendRedirect("/index.html");
        return AppResult.success();
    }


}
